import { useState, useDeferredValue } from "react"
import { Divider, List, Avatar, Input } from 'antd';
import mockjs from 'mockjs'
interface Item {
    id: number;
    name: string;
    address: string
}

export function UseDeferredValueDemo() {
    console.log('组件渲染')
    const [val, setVal] = useState('')
    const [list, setList] = useState<Item[]>(()=>{
        const data = mockjs.mock({
            'list|5': [
                {
                    'id|+1': 1,
                    name: '@natural',
                    'address': '@county(true)',
                }
            ]
        })
        return data.list
    })


    // react每次重新渲染会死循环
    // setList([...data.list])

    const changeVal = (e: React.ChangeEvent<HTMLInputElement>) => {
        const val = e.target.value
        setVal(val)
    }

    const deferredQuery = useDeferredValue(val)
    // 检查是否为延迟状态
    const isPending = deferredQuery != val

    const findItem = () => {
        console.log('数据变化',val,deferredQuery)
        // 过滤列表，仅在 deferredQuery 更新时触发
        return list.filter((item) => item.name.toString().includes(deferredQuery))

    }

    return (
        <div>
            <h3>UseDeferredValueDemo</h3>
            <Input value={val} onChange={(e) => changeVal(e)} />

            <Divider orientation="left">Default Size</Divider>
            <List
                style={{ opacity: isPending ? 0.2 : 1, transition: 'all 1s' }}
                size="small"
                header={<div>Header</div>}
                footer={<div>Footer</div>}
                bordered
                dataSource={findItem()}
                renderItem={(item, index) => <List.Item>
                    <List.Item.Meta
                        avatar={<Avatar src={`https://api.dicebear.com/7.x/miniavs/svg?seed=${index}`} />}
                        title={item.name}
                        description={item.address}
                    />
                </List.Item>}
            />

        </div>
    )
}